//
//  ICMTitleTextFeildView.m
//  ICrEAM
//
//  Created by FoREVer_SaD on 16/10/26.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "ICMTitleTextFeildView.h"
#import "PopoverSelectionViewController.h"

#define DEFTitleColor    TitleColor_Dark

@interface ICMTitleTextFeildView ()<PopoverSelectionViewControllerDelegate,UITextFieldDelegate>{
    BOOL canEdit;
}

@property (nonatomic, weak) id target;
@property (nonatomic, assign) SEL selector;
@property(nonatomic,weak)UIView *contentView;
@end

@implementation ICMTitleTextFeildView


//赋值和获取输入框内容时指向textFeild
- (NSString *)contentText{
    return self.contentTextFeild.text?self.contentTextFeild.text:@"";
}

- (void)setContentText:(NSString *)contentText{
    self.contentTextFeild.text = contentText;
}

- (instancetype)initEditableViewWithFrame:(CGRect)frame title:(NSString *)title{
    if (self = [super initWithFrame:frame]) {
        
        CGSize titleSize = [title sizeWithAttributes:@{NSFontAttributeName:BoldTitleFont}];
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, titleSize.width, titleSize.height)];
        [titleLabel setUpLabelWithText:title alignment:NSTextAlignmentLeft textSize:TitleSize textColor:DEFTitleColor];
        [self addSubview:titleLabel];
        self.titleLabel = titleLabel;
        
        if([titleLabel.text isEqualToString:@"当前行驶里程(KM)"]){
            
            _mileageLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(titleLabel.frame), titleLabel.frame.origin.y, 100, titleLabel.size.height)];
            _mileageLabel.backgroundColor = [UIColor clearColor];
            _mileageLabel.font = [UIFont systemFontOfSize:14];
            _mileageLabel.textColor = [UIColor lightGrayColor];
            _mileageLabel.textAlignment = NSTextAlignmentCenter;
            [self addSubview:_mileageLabel];
            
        }

        UIView *borderView = [[UIView alloc] initWithFrame:CGRectMake(0, DistanceOfTitleToText+titleSize.height, frame.size.width, TextFeildHeight)];
        borderView.backgroundColor = TextFeildBackgroundColor_OffWhite;
        CornerRadius(borderView, RadiusValue);
        BorderColor(borderView, BorderColor_Gray_Hex);
        BorderWidth(borderView, 1.0);
        [self addSubview:borderView];
        self.borderView = borderView;
        
        UITextField *contentTextFeild = [[UITextField alloc] initWithFrame:CGRectMake(ActualWidth(10), DistanceOfTitleToText+titleSize.height, frame.size.width-ActualWidth(20), TextFeildHeight)];
        contentTextFeild.font = ContentFont;
        contentTextFeild.placeholder = @"请输入";
        canEdit=YES;
        contentTextFeild.delegate = self;
        [self addSubview:contentTextFeild];
        self.contentTextFeild = contentTextFeild;
    }
    return self;
}

- (void)setLimitedNum:(NSInteger)limitedNum {
    _limitedNum = limitedNum;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:) name:@"UITextFieldTextDidChangeNotification" object:self.contentTextFeild];
}

- (void)textFiledEditChanged:(NSNotification *)obj {
   
    UITextField *textField = (UITextField *)obj.object;
    NSString *toBeString = textField.text;
    
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    
    //小写转大写
    if (self.isUppercase) {
        NSString *toBeString = textField.text;
        NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
        if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
            UITextRange *selectedRange = [textField markedTextRange];
            //获取高亮部分
            UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
           
            // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
            if (!position) {
                textField.text= toBeString.uppercaseString;
            }else{
                // 有高亮选择的字符串
            }
            
            textField.text = textField.text;
        }else {
            textField.text = textField.text.uppercaseString;
        }
        
        
        if(textField.text.length > self.limitedNum && self.limitedNum != 0)
        {
            textField.text = [textField.text substringToIndex:self.limitedNum];
        }
        
       
    }
    
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position)
    {
        if (toBeString.length > self.limitedNum)
        {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:self.limitedNum];
            if (rangeIndex.length == 1)
            {
                textField.text = [toBeString substringToIndex:self.limitedNum];
            }
            else
            {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, self.limitedNum)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
//    if ([self.delegate respondsToSelector:@selector(editableViewDidEndEdit:)]) {
//        [self.delegate editableViewDidEndEdit:self];
//    }
    if ([self.delegate respondsToSelector:@selector(textFiledShouldReturnClickWithView:)]) {
        [self.delegate textFiledShouldReturnClickWithView:self];
    }
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if (!canEdit) {
        return NO;
    }
    if(textField.text.length > self.limitedNum && self.limitedNum != 0)
    {
        textField.text = [textField.text substringToIndex:self.limitedNum];
    }
    return canEdit;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    if ([self.delegate respondsToSelector:@selector(editableViewDidEndEdit:)]) {
        [self.delegate editableViewDidEndEdit:self];
    }
    //值变化
    if([self.delegate respondsToSelector:@selector(iCMTitleTextFeildViewValueChanged)])
    {
        [self.delegate iCMTitleTextFeildViewValueChanged];
    }
    
    return YES;
}

- (instancetype)initNoneditableViewWithFrame:(CGRect)frame title:(NSString *)title{
    if (self = [super initWithFrame:frame]) {
        
        CGSize titleSize = [title sizeWithAttributes:@{NSFontAttributeName:BoldTitleFont}];
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, titleSize.width, titleSize.height)];
        [titleLabel setUpLabelWithText:title alignment:NSTextAlignmentLeft textSize:TitleSize textColor:DEFTitleColor];
        [self addSubview:titleLabel];
        self.titleLabel = titleLabel;
        
        UIView *borderView = [[UIView alloc] initWithFrame:CGRectMake(0, DistanceOfTitleToText+titleSize.height, frame.size.width, TextFeildHeight)];
        borderView.backgroundColor = TextFeildBackgroundColor_Gray;
        CornerRadius(borderView, RadiusValue);
        BorderColor(borderView, BorderColor_Gray_Hex);
        BorderWidth(borderView, 1.0);
        [self addSubview:borderView];
        self.borderView = borderView;
        
        UITextField *contentTextFeild = [[UITextField alloc] initWithFrame:CGRectMake(ActualWidth(10), DistanceOfTitleToText+titleSize.height, frame.size.width-ActualWidth(20), TextFeildHeight)];
        contentTextFeild.font = ContentFont;

        contentTextFeild.inputView=[[UIView alloc] initWithFrame:CGRectZero];
        contentTextFeild.inputAccessoryView=[[UIView alloc] initWithFrame:CGRectZero];
        contentTextFeild.tintColor = [UIColor clearColor];
        UITextInputAssistantItem *item= contentTextFeild.inputAssistantItem;
        item.leadingBarButtonGroups = @[];
        item.trailingBarButtonGroups = @[];
        
        
//    [contentTextFeild.undoManager  disableUndoRegistration];
//    [textField.undoManager removeAllActions];
        contentTextFeild.delegate=self;
        canEdit=NO;
        [self addSubview:contentTextFeild];
        
//        UIButton *btn=[[UIButton alloc]initWithFrame:contentTextFeild.frame];
//        [btn addTarget:self action:@selector(copyItemClick:) forControlEvents:UIControlEventTouchUpInside];
//        [self insertSubview:btn aboveSubview:contentTextFeild];
        self.contentTextFeild = contentTextFeild;
    }
    return self;
}

-(void)copyText:(id)sender{
    
}
-(void)copyItemClick:(id)sender{
    UIButton *btn=sender;

 
}

- (instancetype)initNoneditableViewRedWithFrame:(CGRect)frame title:(NSString *)title{
    if (self = [super initWithFrame:frame]) {
        
        CGSize titleSize = [title sizeWithAttributes:@{NSFontAttributeName:BoldTitleFont}];
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, titleSize.width, titleSize.height)];
        [titleLabel setUpLabelWithText:title alignment:NSTextAlignmentLeft textSize:TitleSize textColor:[UIColor redColor]];
        [self addSubview:titleLabel];
        self.titleLabel = titleLabel;
        
        UIView *borderView = [[UIView alloc] initWithFrame:CGRectMake(0, DistanceOfTitleToText+titleSize.height, frame.size.width, TextFeildHeight)];
        borderView.backgroundColor = TextFeildBackgroundColor_Gray;
        CornerRadius(borderView, RadiusValue);
        BorderColor(borderView, BorderColor_Gray_Hex);
        BorderWidth(borderView, 1.0);
        [self addSubview:borderView];
        self.borderView = borderView;
        
        UITextField *contentTextFeild = [[UITextField alloc] initWithFrame:CGRectMake(ActualWidth(10), DistanceOfTitleToText+titleSize.height, frame.size.width-ActualWidth(20), TextFeildHeight)];
        contentTextFeild.font = ContentFont;
        contentTextFeild.userInteractionEnabled = NO;
        [self addSubview:contentTextFeild];
        self.contentTextFeild = contentTextFeild;
    }
    return self;
}

- (instancetype)initClickableViewWithFrame:(CGRect)frame title:(NSString *)title addTarget:(id)target selector:(SEL)selector{
    if (self = [super initWithFrame:frame]) {
        self.target = target;
        self.selector = selector;
        
        CGSize titleSize = [title sizeWithAttributes:@{NSFontAttributeName:TitleFont}];
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, titleSize.width, titleSize.height)];
        [titleLabel setUpLabelWithText:title alignment:NSTextAlignmentLeft textSize:TitleSize textColor:DEFTitleColor];
        [self addSubview:titleLabel];
        self.titleLabel = titleLabel;
        
   
        UIView *borderView = [[UIView alloc] initWithFrame:CGRectMake(0, DistanceOfTitleToText+titleSize.height, frame.size.width, TextFeildHeight)];
        borderView.backgroundColor = TextFeildBackgroundColor_OffWhite;
        CornerRadius(borderView, RadiusValue);
        BorderColor(borderView, BorderColor_Gray_Hex);
        BorderWidth(borderView, 1.0);
        [self addSubview:borderView];
        self.borderView = borderView;
        UIView *contentview=[[UIView alloc]initWithFrame:CGRectMake(0, DistanceOfTitleToText+titleSize.height, frame.size.width, TextFeildHeight)];
        
                                                             
        UITextField *contentTextFeild = [[UITextField alloc] initWithFrame:CGRectMake(ActualWidth(10), 0, frame.size.width-ActualWidth(20), TextFeildHeight)];
        contentTextFeild.font = ContentFont;
        contentTextFeild.placeholder = @"请选择";
        contentTextFeild.userInteractionEnabled = NO;
        [contentview addSubview:contentTextFeild];
        [self addSubview:contentview];
        self.contentView=contentview;
        self.contentTextFeild = contentTextFeild;
        
        UIButton *contentTextButton = [[UIButton alloc]initWithFrame:CGRectMake(0, DistanceOfTitleToText+titleSize.height, frame.size.width, TextFeildHeight)];
        contentTextButton.backgroundColor = [UIColor clearColor];
        [contentTextButton setUpButtonWithNormolTitle:nil selectedTitle:nil normolTitleSize:0 selectedTitleSize:0 normolTitleColor:nil selectedTitleColor:nil normolBcakImage:nil selectedBackImage:nil actionSEL:@selector(contentTextButtonAction:) target:self];
        [self addSubview:contentTextButton];
        self.contentTextButton = contentTextButton;
    }
    return self;
}
-(void)setBtnEnAble:(BOOL)btnEnAble{
    _btnEnAble = btnEnAble;
//    if (!btnEnAble) {
//        self.contentView.backgroundColor=TextFeildBackgroundColor_Gray;
//    }
    if(!_btnEnAble)
    {
        self.borderView.backgroundColor = TextFeildBackgroundColor_Gray;
        
    }
    self.contentTextButton.userInteractionEnabled = btnEnAble;
}

- (void)contentTextButtonAction:(UIButton*)sender{
    [self.superview endEditing:YES];
    if ([self.target respondsToSelector:self.selector]) {
        if ([NSStringFromSelector(self.selector) hasSuffix:@":"]) {
            IMP imp = [self.target methodForSelector:self.selector];
            void (*func)(id, SEL, id) = (void *)imp;
            func(self.target, self.selector, self);
        }else{
            IMP imp = [self.target methodForSelector:self.selector];
            void (*func)(id, SEL) = (void *)imp;
            func(self.target, self.selector);
        }
    } else {
        if (self.clickDataArray
            &&
            self.clickDataArray.count) {
            //[ICrEAMTool showPopoverSelectionViewWithSourceView:sender displayWidth:sender.width displayHeight:sender.height dataArray:self.clickDataArray delegate:self showType:PopoverSelectionViewShowTypeTable];
            if([self.titleLabel.text isEqualToString:@"所在省（市）"])
            {
                [ICrEAMTool showPopoverSelectionViewWithSourceView:sender displayWidth:sender.width displayHeight:sender.height dataArray:self.clickDataArray delegate:self showType:PopoverSelectionViewShowTypeTable IsMultiSelect:self.isMultiSelect WithSelectedStr:self.contentTextFeild.text WithPermittedArrowDirections:@"UP"];
            }
            else
            {
                [ICrEAMTool showPopoverSelectionViewWithSourceView:sender displayWidth:sender.width displayHeight:sender.height dataArray:self.clickDataArray delegate:self showType:PopoverSelectionViewShowTypeTable IsMultiSelect:self.isMultiSelect WithSelectedStr:self.contentTextFeild.text WithPermittedArrowDirections:@"DOWN"];
            }
            
        }
    }
}

- (void)getSelectedTitle:(NSString *)string {
    self.contentTextFeild.text = string;
    //值变化
    if([self.delegate respondsToSelector:@selector(iCMTitleTextFeildViewValueChanged)])
    {
        [self.delegate iCMTitleTextFeildViewValueChanged];
    }
}

- (void)didSelectDataAtIndex:(NSInteger)index
{
    if(self.clickDataNoArray && self.clickDataNoArray.count > 0)
    {
        self.noStr = self.clickDataNoArray[index];
    }
    self.selectIndex = index;
    if([self.delegate respondsToSelector:@selector(clickedData:)])
    {
        [self.delegate clickedData:self];
    }
}

+ (instancetype)createEditableICMTitleTextFeildViewWithFrame:(CGRect)frame title:(NSString *)title{
    return [[ICMTitleTextFeildView alloc] initEditableViewWithFrame:frame title:title];
}

+ (instancetype)createNoneditableICMTitleTextFeildViewWithFrame:(CGRect)frame title:(NSString *)title{
    return [[ICMTitleTextFeildView alloc] initNoneditableViewWithFrame:frame title:title];
}

+ (instancetype)createClickableICMTitleTextFeildViewWithFrame:(CGRect)frame title:(NSString *)title addTarget:(id)target selector:(SEL)selector{
    return [[ICMTitleTextFeildView alloc] initClickableViewWithFrame:frame title:title addTarget:target selector:selector];
}

+ (instancetype)createNoneditableICMTitleTextFeildViewRedWithFrame:(CGRect)frame title:(NSString *)title{
    return [[ICMTitleTextFeildView alloc] initNoneditableViewRedWithFrame:frame title:title];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"UITextFieldTextDidChangeNotification" object:self.contentTextFeild];
}

@end
